/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Table, TableBody, TableRow, CCell, TableHead, Text, useTheme, Button,
} from "customize-easy-ui-component";
import {DirectLink, Link as RouterLink,} from "../../../routing/Link";
import { ReportViewProps, } from "../../common/base";
import {末尾链接, 落款单位地址,} from "../../common/rarelyVary";
import {config报告设备, 首页设备概况WalSS,} from "./repView";
import {useRepMenuDirItems, } from "../../hook/useMainRepUrlOr";
import {setupItemAreaRoute} from "./orcIspConfig";
import queryString from "query-string";
import {FormatOriginal, } from "./FormatOriginal";
import RoutingContext from "../../../routing/RoutingContext";
import {useContext} from "react";
import {useLikeSafeEvalOfficial} from "../hook/useLikeSafeEvalOfficial";
import {检验编制核准EvalS, 注意事项WalkSa,} from "../rarelyVary";
import {UnqualifiedIspTableEvalSplit} from "../general";
import {useItemsMapEval} from "../config";
import {useCalcEvalTotalScore} from "../hook/useCalcEvalTotalScore";
import {floatInterception} from "../../../common/tool";
import {运行速度偏差} from "./SpeedBias";
import {扶手带速度偏差} from "./HandrailBias";
import {运行振动评价表} from "./VibrationEval";
import {报告检测仪器} from "../scieEleva/repView";
import {ReportFirstPageHeadJd} from "../../park/rarelyVary";
import {ConclusionVw} from "./Conclusion";
import {设备概况页} from "../../park/views";


export const ReportView: React.FunctionComponent<ReportViewProps> = ({
repId,  source: orc,  verId,rep,
}) => {
    const qs= queryString.parse(window.location.search);
    const formatOriginal =qs && !!qs.original;      //改成  格式化版原始记录
    const { history } = useContext(RoutingContext);
    const Component=formatOriginal? FormatOriginal : OfficialReport;
    return (<>
        <Component  source={orc} verId={verId} repId={repId} rep={rep}/>
        <div css={{margin: '0.5rem', "@media print": {display: 'none'} }}>
            <Button intent="danger" variant="outline"
                  onPress={async () => {
                      qs.original =formatOriginal? '' : '1';
                      history.location.search = queryString.stringify(qs);
                      const toUrl= history.createHref(history.location);
                      history.push(toUrl);
                  }}>{formatOriginal? '正式报告':'格式化版原始记录'}
            </Button>
        </div>
    </>);
}

const unqTitles=[['A','表1 存在一定安全风险必须整改的项目'],
    [undefined,'表2 具有一定潜在安全风险建议整改的项目'],
    ['B','表3 采用旧的制造与安装技术建议整改的项目']
];
//页面哈希路由方式
const JumpTags=[{name:'设备概况',ha:'Survey'},{name:'表1存在一定安全风险必须整改项',ha:'ReCheckA'},
                 {name:'1.1驱动系统U1',ha:'1.1'},{name:'7.1梯路系统U2',ha:'7.1'},{name:'36.1电气控制系统U5',ha:'36.1'},{name:'附录B空载和扶手带运行速度偏差',ha:'HandrailBias'}];
/**直板手机目前超过6英寸，竖屏的(2024年见的)1.5K 2K分辨率的宽度有411px情形下的报告导航情况看似可以接受。横屏后2个半边效果比360px宽的手机好多了。
 * 本模板异常？： 原始记录和报告不符合常规一一对应，有些自拆分项目没有体现到报告的项目行当中。
 * */
const OfficialReport: React.FunctionComponent<ReportViewProps> = ({
    repId,   source: orc,  verId,rep,
}) => {
    const qs= queryString.parse(window.location.search);
    const printing =qs && !!qs.print;
    const theme= useTheme();
    const [rootMenu]=useRepMenuDirItems(JumpTags, [],`/reportView/${rep?.modeltype}/ver/${verId}/${repId}`);
    const impressionismAs =React.useMemo(() => {
        return setupItemAreaRoute({rep,orc, theme});
    }, [verId, repId, theme]);
    // const itRes =React.useMemo(()=>检验结果替换(orc), [orc]);
    const {renderIspContent} =useLikeSafeEvalOfficial({itRes:orc,ItemArs:impressionismAs?.Item, model:rep?.modeltype,ver:verId, repId:repId!});
    const [mapNoTag]=useItemsMapEval({ ItemArs:impressionismAs?.Item, });
    const evalTotalScore=floatInterception(useCalcEvalTotalScore({itRes:orc, ItemArs:impressionismAs?.Item}),2);
   return (
       <React.Fragment>
           {rootMenu}
           <div css={{"@media not print": {marginTop: '1rem', marginBottom: '1rem'}}}>
               <div css={{"@media print": {height: '100vh'}}}>
                   {ReportFirstPageHeadJd({theme, rep, mbbm: 'FJB/TP-1006-2-2020'})}
                   <div css={{
                       "@media print": {
                           display: 'flex',
                           flexDirection: 'column',
                           justifyContent: 'space-between',
                           height: 'calc(100vh - 8.5rem)',
                       }
                   }}>
                       <Text variant="h3" css={{
                           textAlign: 'center',
                           "@media print": {fontSize: theme.fontSizes[5], marginTop: '1.5rem',},
                       }}>
                         自动扶梯与自动人行道安全性能技术评估(科研类)报告
                       </Text>
                       {首页设备概况WalSS({theme, orc, rep})}
                       <div css={{
                           textAlign: 'center',
                           "@media print": {pageBreakAfter: 'always', pageBreakInside: 'avoid'}
                       }}>
                           {落款单位地址}
                       </div>
                   </div>
               </div>
               {注意事项WalkSa({
                   rep,
                   comply: '适用于自动扶梯或自动人行道安全性能技术评估'
               })}
               <DirectLink href={`/report/${rep?.modeltype}/ver/${verId}/${repId}/Instrument`}>
                   <div css={{
                       display: 'flex',
                       flexDirection: 'column',
                       justifyContent: 'center',
                       "@media print": {pageBreakBefore: 'always',},
                   }}>
                       <Text variant="h4">一、设备概况</Text>
                   </div>
               </DirectLink>
               {设备概况页({orc, rep, config: config报告设备, theme, fixed: ["5%", "7.1%", "38%", "7.1%", "5%", "%"]})}
               <Text variant="h4" css={{
                   "@media print": {marginTop: '1rem',},
               }}>二、评估依据</Text>
               1、科技成果：《基于模糊层次分析法的扶梯安全风险评估研究》（FJQI2013070）<br/>
               2、DB35/T 1936-2020《自动扶梯和自动人行道运行振动测量和评价》
               {报告检测仪器({orc, repId: repId!, verId, rep})}
               <ConclusionVw orc={orc} rep={rep} evalTotalScore={evalTotalScore!} label={'四、评估结论'}/>
               {检验编制核准EvalS({orc, rep})}

               <UnqualifiedIspTableEvalSplit rep={rep} orc={orc} mapNoTag={mapNoTag} printing={printing}
                                             config={unqTitles}/>

               <div css={{"@media print": {paddingBottom: '4.5rem', pageBreakInside: 'avoid'}}}>
                   <Text variant="h4" css={{
                       marginTop: '1rem',
                   }}>五、评估项目表</Text>
               </div>
               <Table fixed={["3%", "6%", "8%", "8%", "%", "8%", "5%", "6%", "6%", "5%", "6%"]}
                      css={{borderCollapse: 'collapse', "@media print": {marginTop: '-4.5rem'}}} tight miniw={800}>
                   <TableHead>
                       <DirectLink href={`/report/${rep?.modeltype}/ver/${verId}/${repId}/ALL`}>
                           <TableRow>
                               <CCell>序号</CCell>
                               <CCell colSpan={2}>项目</CCell>
                               <CCell>项目编号</CCell>
                               <CCell>评估内容与要求</CCell>
                               <CCell>检测结果</CCell>
                               <CCell>严重程度</CCell>
                               <CCell>风险频率</CCell>
                               <CCell>风险类别</CCell>
                               <CCell>权重</CCell>
                               <CCell>得分</CCell>
                           </TableRow>
                       </DirectLink>
                   </TableHead>
                   <TableBody>
                       {renderIspContent}
                   </TableBody>
               </Table>
               <Text css={{textIndent: '1.6rem', display: 'flex', fontSize: '0.8rem'}}>
                   备注：项目编号后A表示必须整改项目、B表示现行安全技术规范或标准新要求的项目，无标注的表示建议整改项目，标有※的项目为应当遵循“水桶短板理论”的评估项目。
               </Text>
               {运行速度偏差({orc, rep, label: '附录A 空载梯级（踏板、胶带）运行速度与名义速度偏差（简易方法）'})}
               {扶手带速度偏差({orc, rep, label: '附录B 空载梯级（踏板、胶带）和扶手带运行速度偏差（简易方法）'})}
               {运行振动评价表({orc, rep, label: '附录C 自动扶梯和自动人行道运行振动评价表'})}
           </div>
           <div>
               <RouterLink href={`/report/${rep?.modeltype}/ver/${verId}/${repId}/Instrument?original=1#Instrument`}>
                   <Text variant="h4" css={{"@media print": {display: 'none'}}}>主要测量设备性能检查</Text>
               </RouterLink>
               <RouterLink href={`/report/${rep?.modeltype}/ver/${verId}/${repId}/SiteCondition#SiteCondition`}>
                   <Text id={'SiteCondition'} variant="h4"
                         css={{"@media print": {display: 'none'}}}>附录：现场检测条件确认</Text>
               </RouterLink>
           </div>
           {末尾链接({template: rep?.modeltype, verId, repId: repId || ''})}
       </React.Fragment>
   );
}
